<template>
  <div style="padding:20px;">
    <h2>登录 / 注册</h2>
    <input v-model="username" placeholder="用户名" />
    <input v-model="password" type="password" placeholder="密码" />
    <div style="margin-top:8px;">
      <button @click="onLogin">登录</button>
      <button @click="onRegister">注册</button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

const username = ref('');
const password = ref('');
const router = useRouter();

async function onLogin() {
  try {
    const res = await axios.post('http://localhost:3000/auth/login', { username: username.value, password: password.value });
    localStorage.setItem('token', res.data.access_token);
    router.push('/chat');
  } catch (e) {
    alert('login failed');
  }
}
async function onRegister() {
  try {
    const res = await axios.post('http://localhost:3000/auth/register', { username: username.value, password: password.value });
    localStorage.setItem('token', res.data.access_token);
    router.push('/chat');
  } catch (e) {
    alert('register failed');
  }
}
</script>
